#include <iostream>
#include <fstream>
#include <string>
#include <time.h>
#include <vector>
#include <cstring>
#include <sstream>

#include <boost/filesystem.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/filesystem/fstream.hpp>>

#include "stn/FileUtils.h"
#include "stn/stn_libssh_shorts.h"




using namespace std;
using namespace boost::filesystem;




//string allVars[]={"LOCAL_ROOT: ", "REMOTE_ROOT: "};
string localRoot;
string remoteRoot;
string SSH;
string PASSWORD;
string user;
int port;
std::vector<string> commands;
FileResult fileResult;
char *currentFolderLocation;


void processData(string relativePath, ssh_scp scp);

void giveValues(){
	 ObjectsFromFile *objects=new ObjectsFromFile("demo.txt");
	 localRoot=objects->getPropertyByName("LOCAL_ROOT");
	 SSH=objects->getPropertyByName("SSH");
	 PASSWORD=objects->getPropertyByName("PASSWORD");
	 remoteRoot=objects->getPropertyByName("REMOTE_ROOT");
	 user=objects->getPropertyByName("USER");
	 port=atoi(objects->getPropertyByName("PORT").c_str());
	 delete objects;
}




char * charToString(string someData){
	char *rchr=new char[someData.size()+1];
	rchr[someData.size()]=0;
	memcpy(rchr,someData.c_str(),someData.size());
	return rchr;
}










//void processData(string relativePath){
//	string command;
//	command="expect -c 'spawn scp "+localRoot+relativePath+" "+SSH+":"+remoteRoot+relativePath+"; expect assword; send "+"\""+PASSWORD+"\n\"; interact'";
//
//	//string builtInSh="./scpTool.sh LOCAL='"+localRoot+relativePath+"' "+remoteRoot+relativePath+" "+SSH+" "+PASSWORD;
//	string builtInSh="LOCAL='"+localRoot+"' REMOTE='"+remoteRoot+"' RELATIVE_PATH='"+relativePath+"' SSH="+SSH+" PASSWORD="+PASSWORD+" ./scpTool.sh";
//
//char comanda[builtInSh.size()];
//for(int a=0; a<(int) builtInSh.size(); a++){
//	comanda[a]=builtInSh[a];
//}
//
//cout.flush();
//system(builtInSh.c_str());// unde c_str() nu altereaza stringul
//
//}



string getLocalContent(string path){
	boost::filesystem::path fileName(path);
	boost::filesystem::ifstream inFile(fileName);
	string content;
		while ( inFile )
		{
		  std::string s;
		  std::getline( inFile, s );
		  if (inFile)
			  content.append(s);
		  	  content.append("\n");
		    //std::cout << s << "\n";
		}

		return content;
}



void processData(string relativePath, ssh_scp scp){
	cout << "lucrez cu " << relativePath << endl;
	//string originalRelPat=relativePath;
	//char *str1 = const_cast<char*>(relativePath.c_str());

	//char *str1 = const_cast<char*>(relativePath.c_str());

	//char str2[] = "/";
	//char * pnt;
	//pnt=strtok( str1, str2 );

	vector<char*> listItems;
	std::istringstream iss(relativePath);
	string token;
	int num=-1;


	while(getline(iss, token, '/'))
	{
		num++;
		char *cstr = new char[token.length() + 1];
		strcpy(cstr, token.c_str());
	      std::cout << token << std::endl;
	      listItems.push_back(cstr);
	      delete [] cstr;
	}

	int rc;
	int lung=(int) listItems.size();

	//cream foldere daca nu exista:
	for(int i=0; i<lung-1; i++){
		rc = ssh_scp_push_directory(scp, listItems.at(i), S_IRWXU);
//		if (rc != SSH_OK){
//			fprintf(stderr, "Can't create remote directory:\n");
//		}
	}
	string path=localRoot+"/"+listItems.at(listItems.size()-1);
	//scoate enterul din stdout
	relativePath.erase(std::remove(relativePath.begin(), relativePath.end(), '\n'), relativePath.end());
	string total=localRoot+relativePath;
	//getLocalContent(total);

	char *content="file content here";
	char *fileName="fileNameInhere.txt";
	int length = strlen(content);

	//suprascriem fisierul
	rc = ssh_scp_push_file(scp, fileName, length, S_IRUSR |  S_IWUSR);
	  if (rc != SSH_OK)
	  {
	    fprintf(stderr, "Can't open remote file: %s\n");
	  }

	  rc = ssh_scp_write(scp, content, length);
	  if (rc != SSH_OK)
	  {
	    fprintf(stderr, "Can't write to remote file: %s\n");
	  }



}


string composeSvnQuery(){
	string result;
	result.append("svn status ");
	result.append(localRoot);
	return result;
}

string accuratePath;
				string relativeFilePath;

void executeSvnLine(string tdata, ssh_session session, sftp_session sftp){
		//string tdata=string(buffer);

	cout << tdata << endl;

		string::size_type indexOf=tdata.find("/");


		if(indexOf != std::string::npos) {
			accuratePath="/"+tdata.substr(indexOf+1);
			//cout << "    accurate : " << accuratePath << endl;
			relativeFilePath=accuratePath.replace(0, localRoot.length(), "");
			relativeFilePath.erase(std::remove(relativeFilePath.begin(), relativeFilePath.end(), '\n'), relativeFilePath.end());
			commands.push_back(relativeFilePath);
		}





		string totalLocal=localRoot+relativeFilePath;
		string totalRemote=remoteRoot+relativeFilePath;




		string fileContent=getLocalContent(totalLocal);
		if(fileContent.length()>0){
			cout << "---LOCAL ROOT--------: " << localRoot << endl;
			cout << "---RELATIVE PATH-----: " << relativeFilePath << endl;
			cout << "---TOTAL REMOTE PATH-: " << totalRemote << endl;
			cout << "---TOTAL LOCAL PATH--: " << totalLocal << endl;
			cout << "---TOTAL LOCAL FILE CONTENT -----------: \n" << fileContent << endl;

	//		char * temp="/usr/local/apache-tomcat-6.0.35/webapps/ROOT/js/privateShow/html2canvas.js";

			char * S = new char[totalRemote.length() + 1];
			std::strcpy(S,totalRemote.c_str());

			stn_sftp_copyToRemote(session, sftp, S, fileContent.c_str());
		}else{

			cout << "----------FAILED TO LOAD " << totalLocal << " -------"<< endl;
		}


		//processData(relativeFilePath, scp);
}




void copyToRemote(ssh_session session, sftp_session sftp){




			int lung=fileResult.getLines().size();
			cout << " ----- TRANSLATING  " << lung << " FILES ---- "<< endl;
				for(int s=0; s<lung; s++){
					cout << " \n ---------------- CONNECTED TO REMOTE HOST TO WRITE SVN COMMAND >> " << fileResult.getLines().at(s) << endl;
					executeSvnLine(fileResult.getLines().at(s), session, sftp);
				}
}



void connectToWrite(ssh_session session){
	//cout << "connect to folder "  << remoteRoot << endl;
	//scp_connectToWrite(session, charToString(remoteRoot), &copyToRemote);

	cout << "----SSH CONNECTION MADE --- " << endl;
	stn_sftp_connect(session, &copyToRemote);
}




int main(int argc,char* argv[])
{
	giveValues();
	cout << "LOCAL ROOT:" << localRoot << endl;
	fileResult=stn_getStdOutFromCommand(composeSvnQuery());
	cout << "EXECUTE SVN COMMAND" << endl;
	fileResult.printLines();
//
//
////	return 1;
	stn_connectToRemoteServer(charToString(SSH), charToString(PASSWORD), SSH_LOG_PROTOCOL, port, &connectToWrite);
    return 0;
}
